var dgram = require('dgram');
var udp_client = dgram.createSocket('udp4');
var robot = require("robotjs"); 

udp_client.on('close', function () {
    console.log('udp client closed.')
})

//错误处理
udp_client.on('error', function () {
    console.log('some error on udp client.')
})

// 接收消息
udp_client.on('message', function (msg, rinfo) {
    console.log(`receive message from ${rinfo.address}:${rinfo.port}：${msg}`);
})

//发送键值
function send_key(key) {
    var obj = {}
    obj.key = key

    var SendBuff = JSON.stringify(obj)
    var SendLen = SendBuff.length;
    var ip = '192.168.51.221'
    udp_client.send(SendBuff, 0, SendLen, 1000, ip);
    console.log("\r\n发送消息", ip, SendBuff)
}

var stdin = process.stdin;

// without this, we would only get streams once enter is pressed
stdin.setRawMode(true);

// resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
stdin.resume();

// i don't want binary, do you?
stdin.setEncoding('utf8');

// on any data into stdin
stdin.on('data', function (key) {
    // ctrl-c ( end of text )
    if (key === '\u0003') {
        process.exit();
    }

    send_key(key)
    // write the key to stdout all normal like
    process.stdout.write(key);
});